package com.xpec.cipher.handler;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xpec.cipher.CipherConnectionConstant;
import com.xpec.cipher.CipherConnectionStatus;
import com.xpec.cipher.CipherHandler;
import com.xpec.cipher.tals.TalsConstance;
import com.xpec.net.xnetty.cihper.XNettyCipherHandler;

public class ClientReceiveServerCipherHandler implements CipherConnectionPacketHandler 
{
	
	private static final Log log = LogFactory.getLog(ClientReceiveServerCipherHandler.class);

	@Override
	public void receiveHandle(CipherHandler cipherHandler) {
		
		// 接收到的是server发过来的HandShake包
		int contentType = cipherHandler.readUnsignedByteFromRealContent();
		if (contentType != TalsConstance.CONTENT_TYPE_CHANGE_CIPHER_SPEC){
			return;
		}

		byte[] serverCipher = new byte[TalsConstance.CHANGE_CIPHER_VERIFY_DATA_SIZE];
		cipherHandler.readByteFromRealContent(serverCipher);
		
		/// 存起來
		cipherHandler.setParameter(CipherConnectionConstant.PARA_KEY_SERVER_CIPHER, serverCipher);
		
		/// 加密握手完成啦  !!!
		cipherHandler.setParameter(CipherConnectionConstant.PARA_KEY_STATUS,
				CipherConnectionStatus.FINISH);
		
		log.info("Cipher is Finish! " + CipherConnectionStatus.FINISH);
		
		/// Client於 FINISH之後改變 pipeline中的 ChannelHandler
		XNettyCipherHandler handler = (XNettyCipherHandler) cipherHandler;
		handler.addOtherChannelHandler();
		
//		System.out.println("Client Tals Finish !");
		
		cipherHandler.notifyCipherFinished();
	}

	@Override
	public void sendHandle(CipherHandler cipherHandler) {
		cipherHandler.passMessage(CipherHandler.PASS_MESSAGE_SEND);
	}

}
